package com.itheima.appserver.service;

import cn.hutool.core.collection.CollUtil;
import com.aliyuncs.utils.StringUtils;
import com.itheima.appserver.exception.BusinessException;
import com.itheima.appserver.interceptor.UserHandler;
import com.itheima.autoconfig.template.OssTemplate;
import com.itheima.dubbo.api.MovementApi;
import com.itheima.dubbo.api.UserInfoApi;
import com.itheima.model.domain.UserInfo;
import com.itheima.model.mongo.Movement;
import com.itheima.model.vo.ErrorResult;
import com.itheima.model.vo.MovementsVo;
import com.itheima.model.vo.PageResult;
import com.itheima.utils.Constants;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class MovementService {
    @Autowired
    private OssTemplate ossTemplate;
    @DubboReference
    private MovementApi movementApi;
    @DubboReference
    private UserInfoApi userInfoApi;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public void publishMovement(Movement movement, MultipartFile[] images) throws IOException {
        //判断发布内容是否存在
        if (StringUtils.isEmpty(movement.getTextContent())) {
            throw new BusinessException(ErrorResult.contentError());
        }
        //获取当前登录的用户id
        Long userId = UserHandler.getId();
        //将文件上传到阿里云，并获取文件地址
        List<String> medias = new ArrayList<>();
        for (MultipartFile image : images) {
            String upload = ossTemplate.upload(image.getOriginalFilename(), image.getInputStream());
            medias.add(upload);
        }
        //封装为movement对象返回
        movement.setUserId(userId);
        movement.setMedias(medias);
        //调用api完成发布
        movementApi.publish(movement);
    }


    private PageResult getPageResult(Integer page, Integer pagesize, List<Movement> list) {
        //判断是否为空movementApi = {proxy2@13259}
        if (CollUtil.isEmpty(list)) {
            return new PageResult();
        }
        //获取集合中的好友ids
        List<Long> ids = CollUtil.getFieldValues(list, "userId", Long.class);
        //调用userinfoapi查询用户详情
        Map<Long, UserInfo> map = userInfoApi.findByIds(ids, null);
        List<MovementsVo> vos = new ArrayList<>();
        //根据每一个movement对象创建vo对象
        for (Movement movement : list) {
            UserInfo userInfo = map.get(movement.getUserId());
            if (userInfo != null) {
                MovementsVo vo = MovementsVo.init(userInfo, movement);
                //修复点赞的bug,判断hashkey是否存在即可
                String key = Constants.MOVEMENTS_INTERACT_KEY + movement.getId().toHexString();
                String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHandler.getId();
                if (redisTemplate.opsForHash().hasKey(key, hashKey)) {
                    vo.setHasLiked(1);
                }
                String hashKey2 = Constants.MOVEMENT_LOVE_HASHKEY + UserHandler.getId();
                if (redisTemplate.opsForHash().hasKey(key, hashKey2)) {
                    vo.setHasLoved(3);
                }
                vos.add(vo);
            }

        }
        return new PageResult(page, pagesize, 0, vos);
    }


    public MovementsVo findone(String id) {
        //根据movementid查询动态
        Movement movement = movementApi.findone(id);
        if (movement == null) {
            //如果没有就返回空
            return null;
        } else {
            //如果有就查询用户详情信息，并进行转换并返回
            UserInfo info = userInfoApi.findById(movement.getUserId());
            return MovementsVo.init(info, movement);
        }

    }

    public PageResult all(Integer page, Integer pagesize, Long userId) {
        //调用api查询分页
        PageResult pr = movementApi.all(page, pagesize, userId);
        //获取items数据
        List<Movement> items = (List<Movement>) pr.getItems();
        if (CollUtil.isEmpty(items)) {
            return pr;
        }
        //调用userinfo查询用户详情
        UserInfo info = userInfoApi.findById(userId);
        //创建vo返回对象
        List<MovementsVo> vos = new ArrayList<>();
        //遍历
        for (Movement item : items) {
            MovementsVo vo = MovementsVo.init(info, item);
            vos.add(vo);
        }
        pr.setItems(vos);
        return pr;
    }

    public PageResult RecommendMovemet(Integer page, Integer pagesize) {
        //存入redis缓存中
        //创建key
        String rediskey = Constants.MOVEMENTS_INTERACT_KEY + UserHandler.getId();
        //获取指定key中的数据
        String redisData = redisTemplate.opsForValue().get(rediskey);//{12,2,3,6,5}
        //判断数据是否为空
        //创建动态集合
        List<Movement> list = new ArrayList<>();
        if (StringUtils.isEmpty(redisData)) {
            //为空生成随机动态返回
            list = movementApi.getRandom(pagesize);
        } else {
            //不为空,获取数据
            //根据符号切割
            String[] split = redisData.split(",");
            //判断分页的临界
            if ((page - 1) * pagesize > split.length) {
                return new PageResult();
            }
            //根据流的转换,转换为pid的集合
            List<Long> pids = Arrays.stream(split).skip((page - 1) * pagesize).limit(pagesize)
                    .map(e -> Long.valueOf(e))//使流中的每一个数据转换为long类型
                    .collect(Collectors.toList());
            //根据集合查询动态列表
            list = movementApi.findPids(pids);
        }
        return getPageResult(page, pagesize, list);
    }

    public PageResult FriendMovement(Integer page, Integer pagesize) {
        //获取当前用户id
        Long userId = UserHandler.getId();
        //调用api查询分页
        List<Movement> list = movementApi.FriendMovement(userId, page, pagesize);
        //判断是否为空
        return getPageResult(page, pagesize, list);
    }
}
